package org.millioncall.yueyoga.admin.service.advancedsearch;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorLong;
import com.googlecode.aviator.runtime.type.AviatorObject;

/**
 * 用于在表达式中获取日期年月日的函数
 * 
 * @author zangjinyu
 * @since 1.0.0
 * @version 1.0.0
 * 
 */
public class DateTimeUtilFunction extends AbstractFunction {

	@Override
	public String getName() {
		return "getDateTimeField";
	}

	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1,
			AviatorObject arg2) {
		Date target = (Date) arg1.getValue(env);
		String type = FunctionUtils.getStringValue(arg2, env);// 获取要获得的域类型，是年月日还是时分秒

		if (target == null) {
			return new AviatorLong(0);
		}

		Calendar can = Calendar.getInstance();
		can.clear();
		can.setTime(target);
		long result = 0;
		if ("year".equals(type) || "fullYear".equals(type)) {
			result = can.get(Calendar.YEAR);
		} else if ("month".equals(type)) {
			result = can.get(Calendar.MONTH) + 1;
		} else if ("day".equals(type)) {
			result = can.get(Calendar.DAY_OF_MONTH);
		} else if ("hour".equals(type)) {
			result = can.get(Calendar.HOUR_OF_DAY);
		} else if ("minute".equals(type)) {
			result = can.get(Calendar.MINUTE);
		} else if ("second".equals(type)) {
			result = can.get(Calendar.SECOND);
		}
		return new AviatorLong(result);
	}
}
